package database;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/** 使用c3p0构建的链接池，需配置c3p0的配置文件
 * Description:
 * Created by 4790K_NSL on 2017/5/20.
 */
public class UtilConnectionPool {
    private ComboPooledDataSource dataSource=null;
    private UtilConnectionPool() throws IOException, PropertyVetoException {
        dataSource = new ComboPooledDataSource();
        Properties prop = new Properties();
        InputStream in = UtilConnectionPool.class.getClassLoader().getResourceAsStream("config/c3p0/c3p0.properties");

        prop.load(in);
        String url=prop.getProperty("c3p0.jdbcUrl");
        System.out.println(url);

        dataSource.setDriverClass(prop.getProperty("c3p0.driverClass"));
        dataSource.setJdbcUrl(prop.getProperty("c3p0.jdbcUrl"));
        dataSource.setUser(prop.getProperty("c3p0.user"));
        dataSource.setPassword(prop.getProperty("c3p0.password"));
    }


    private static UtilConnectionPool connectionPool=null;

    public static UtilConnectionPool getInstance() throws IOException, PropertyVetoException {
        if(connectionPool==null){
            synchronized(UtilConnectionPool.class) {
                if(connectionPool==null){
                    connectionPool=new UtilConnectionPool();
                }
            }
        }
        return connectionPool;
    }

   static public DataSource getDatasource() throws IOException, PropertyVetoException {
       getInstance();
       return (DataSource) connectionPool.dataSource;
   }

   static public Connection getConnection() throws IOException, PropertyVetoException, SQLException {
       getInstance();
       return connectionPool.dataSource.getConnection();
   }
}
